package com.nuanshui.framework.utils.http;

import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * http请求的签名
 * @author GH
 *
 */
public class HttpSignUtil {
	private static String appId = "xubnao_http_app_id";
	private static String masterSecret = "e4248ccb-xunbao-43c1-a484-3a6367154409";
	
	private static String inpuCharset = "UTF-8";
	/**
	 * 获取签名前的字符串
	 */
	private  static String createLinkString(HashMap<String,String> map) {
	 			
        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);

		StringBuilder prestr =  new StringBuilder();
        prestr.append("appid="+appId+"&");
        prestr.append("masterSecret="+masterSecret+"&");
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if("sign".equals(key)) continue;
            String value = map.get(key);
            if(value == null) value = "";
            prestr.append(key + "=" + value + "&");
        }	   
        return prestr.toString();
		
	}

	/**
	 * 获取签名
	 * @param @return
	 * @author guohao
	 * @date 2016年8月8日 上午10:24:11
	 * @since $
	 */
	public static String getSign(HashMap<String,String> map) {
		String text = createLinkString(map);
		System.out.println(text);
		String mysign = DigestUtils.md5Hex(getContentBytes(text, inpuCharset));		
		return mysign;
		
	}
	
	
	public static String getSign(Map<String,String[]> map) {
		HashMap<String,String> params = new HashMap<String,String>();
		for(Entry<String,String[]>  entry: map.entrySet()) {
			String key = entry.getKey();
			StringBuilder sb = new StringBuilder();
			for(String str:entry.getValue()) {
				sb.append(str);
			}
			params.put(key, sb.toString());
		}
		return getSign(params);
	}
	
	 /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException 
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }
}
